package middleware

import (
	"github.com/gin-gonic/gin"
	"go_my_framework/app/core/session"
	"go_my_framework/app/global/e"
	"go_my_framework/app/service"
	"go_my_framework/util/base"
	"go_my_framework/util/sli"
	"net/http"
	"strings"
)

// 权限验证中间件
func AuthMiddleware(c *gin.Context) {
	// 当前菜单路径
	url := c.Request.URL.Path
	if strings.HasSuffix(url, "/") {
		url = strings.TrimRight(url, "/")
	}
	if url == e.LoginUrl || url == e.LogoutUrl {
		c.Next()
	} else {
		svc := service.AdminService{}
		if !svc.IsSignedIn(c) {
			base.Redirect(c, http.StatusFound, "/admin/login/login")
			c.Abort()
		} else {
			if !AuthUrl(c, url) {
				base.Redirect(c, http.StatusFound, "/admin/login/notFound")
				c.Abort()
			} else {
				c.Next()
			}
		}
	}
}

func AuthUrl(c *gin.Context, url string) bool {
	// 管理员缓存
	roleId := session.Get(c, "role_id").(int)
	purviewIds := session.Get(c, "purview_ids").([]int)

	// 超级管理员, 属于公共节点
	if roleId == e.SuperRoleId {
		return true
	}

	// 拥有权限
	purviewSvc := service.PurviewService{}
	purviewInfo, _ := purviewSvc.GetRowByUrl(url)
	if sli.InArray(purviewInfo.Id, purviewIds) || IsAllowAuth(url) {
		return true
	}

	return false
}

func IsAllowAuth(url string) bool {
	// 是否属于公共节点
	allowAuth := strings.Split(e.AllowAuth, ",")
	if sli.InArray(url, allowAuth) {
		return true
	}
	return false
}
